package cn.com.template.controller.budgetcalc;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.Workbook;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.commons.Paginator;
import cn.com.commons.utils.CommonUtils;
import cn.com.commons.utils.StringUtil;
import cn.com.dal.dataobject.cs.ProjectDO;
import cn.com.dal.dataobject.cs.SummaryDO;
import cn.com.dal.dataobject.cs.TotalReportEntity;
import cn.com.service.cs.SummaryService;
import cn.com.support.utils.TemplateUtils;
import cn.com.template.ui.Flexigrid;
import cn.com.template.utils.FlexigridUtil;

@Controller
@RequestMapping("/budgetcalc/summary")
public class SummaryController {

	@Autowired
	private SummaryService summaryService;

	@RequestMapping
	public ModelAndView forwardSummary() {
		ModelAndView mav = new ModelAndView("budgetcalc/summary");
		return mav;
	}

	@RequestMapping("/selectForPage.json")
	@ResponseBody
	public Flexigrid selectForPage(HttpServletRequest request,
			HttpServletResponse response) {
		// 封装参数
		Paginator<Object, List<SummaryDO>> paginator = new Paginator<Object, List<SummaryDO>>();
		Integer page = TemplateUtils
				.getParam(Integer.class, request, "page", 1);
		Map<Object, Object> condition = TemplateUtils.bulidBeanMap(request,
				ProjectDO.class);
		// 封装查询时间
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		if (StringUtil.isNotBlank(startTime)) {
			condition.put("startTime", startTime.substring(0,7));
		}
		if (StringUtil.isNotBlank(endTime)) {
			condition.put("endTime", endTime.substring(0,7));
		}
		paginator.setCurrentPage(page);
		paginator.setCondition(condition);

		// 分页查询
		summaryService.selectByPage(paginator);
		// 返回结果
		return FlexigridUtil.formatFlexigridData(paginator);
	}

	@RequestMapping("/exportSummary/{name}/{st}/{et}")
	public void exportSummary(HttpServletRequest request,
			HttpServletResponse response, @PathVariable("name") String name,
			@PathVariable("st") String st, @PathVariable("et") String et) throws UnsupportedEncodingException {
		// 报表数据源
		Map<String, Object> reportDataMap = new HashMap<String, Object>();
		// 表头
		TotalReportEntity reportEntity = new TotalReportEntity();
		// 封装参数
		Map<Object, Object> condition = new HashMap<Object, Object>();
		name = java.net.URLDecoder.decode(name, "UTF-8");
		if (StringUtil.isNotBlank(name) && !name.equals("-1")) {
			condition.put("name", name.trim());
		}
		if (StringUtil.isNotBlank(st) && !st.equals("-1")) {
			condition.put("startTime", st.trim());
			reportEntity.setDateFrom(st);
		}
		if (StringUtil.isNotBlank(et) && !et.equals("-1")) {
			condition.put("endTime", st.trim());
			reportEntity.setDateTo(et);
		}
		reportEntity.setYear(CommonUtils.getCurrentYear());
		reportEntity.setProjectReportLst(summaryService.selectList(condition));
		reportDataMap.put("totalForms", reportEntity);
		// 定义报表生成
		XLSTransformer transformer = new XLSTransformer();
		String path = request.getSession().getServletContext()
				.getRealPath("/WEB-INF/classes");
		String templateFileName = path + "/xlstemp/report.xls";
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(
					templateFileName));
			// Workbook resultWorkbook = transformer.transformXLS(is,
			// reportDataMap);
			response.setHeader("Content-Transfer-Encoding", "base64");
			response.setContentType("application/octet-stream");
			String contentDisposition = "attachment;filename=\"total_report.xls\"";
			response.setHeader("Content-Disposition", contentDisposition);
			OutputStream outputStream = response.getOutputStream();
			transformer.transformXLS(is, reportDataMap).write(outputStream);
			outputStream.flush();
			outputStream.close();
			outputStream = null;
			transformer = null;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
